package com.yunshang.ysmall.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.yunshang.ysmall.model.ProductImgList;
import com.yunshang.ysmall.model.ProductInfo;
import com.yunshang.ysmall.model.ProductTypeInfo;
import com.yunshang.ysmall.service.ProductService;
import com.yunshang.ysmall.service.SupplierService;
import com.yunshang.ysmall.util.DateUtils;

import net.coobird.thumbnailator.Thumbnails;

@Controller
@RequestMapping("/product")
public class ProductController {

	@Resource
	ProductService productService;
	@Resource
	SupplierService supplierService;
	

	public static final String ROOT = "static/upload-dir/";
	
	//后台商品的分页查询
	@RequestMapping("/toprolist")
	public String toprolist(ProductInfo productInfo, Model model) {
		Map params = new HashMap();
		if (productInfo.getProductId() != null && !"".equals(productInfo.getProductId())) {
			params.put("productId", productInfo.getProductId());
		}
		if (productInfo.getProductName() != null && !"".equals(productInfo.getProductName())) {
			params.put("productName", productInfo.getProductName());
		}
		System.out.println("params.productId:" + params.get("productId"));
		params.put("startIndex", 0);
		params.put("pageSize", 10000);
		model.addAttribute("proList", productService.getProductListByMap(params));
		return "/mng/main/product/prolist";
	}

	
	//后台的库存管理
	@RequestMapping("/stocklist")
	public String stocklist(Model model) {
		return "/mng/main/product/table_data_tables";
	}
	//保存商品信息
	@RequestMapping("/savepro")
	public String savepro(@RequestParam MultipartFile smallfile,HttpServletRequest request, ProductInfo productInfo) {
		//从session中查询商品的编号
		String productId = (String) request.getSession().getAttribute("productId");
		System.out.println(productId);
		System.out.println(productInfo.getDetail());
		productInfo.setProductId(productId);
		//判断图片是否为空
		if(!smallfile.isEmpty()){
			String desImgPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath()+ROOT+productId;
			//重新命名图片的名称
			String filePath = upload(desImgPath, smallfile,true);
			//将图片保存到商品信息中
			productInfo.setSmallImgPath(filePath);
		}
		//从session中取出商品图片列表
		List<ProductImgList> itemList = (List<ProductImgList>) request.getSession().getAttribute("itemlist");
		if(itemList != null){
			System.out.println(itemList.size());
			for (int i=0;i < itemList.size();i++) {
				ProductImgList imgItem = itemList.get(i);
				productService.saveProductImg(imgItem);
			}
			request.getSession().removeAttribute("itemlist");
			//保存商品信息
			productService.addProduct(productInfo);
		}
		
		return "redirect:/product/addpro";
	}
	
	@ResponseBody
	@RequestMapping("/savedetailpic")
	public String savedetailimg(String token,HttpServletRequest request) {
		String productId = (String) request.getSession().getAttribute("productId");
		System.out.println("savedetailpic:"+productId);
		Part part;
		try {
			part = request.getPart("myFileName");
		String fi = part.getHeader("content-disposition");
		System.out.println(fi);
		String desImgPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath()+ROOT+productId;
//		try{
//			File destDir = new File(desImgPath);
//			boolean result = destDir.mkdirs();
//			System.out.println("midir result:"+result);
//		}catch (Exception e) {
//			// TODO: handle exception
//			e.printStackTrace();
//		}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "{\"proId\":\"" + productId + "\"}";
	}
	
	@ResponseBody
	@RequestMapping("/saveproimg")
	public String saveimg(HttpServletRequest request, @RequestParam MultipartFile myfiles) {
		String productId = (String) request.getSession().getAttribute("productId");
		System.out.println(productId);
		String desImgPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath()+ROOT+productId;
		try{
			File destDir = new File(desImgPath);
			boolean result = destDir.mkdirs();
			System.out.println("midir result:"+result);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		ProductImgList imgItem = new ProductImgList();
		imgItem.setProductId(productId);
		if (myfiles.isEmpty()) {
			System.out.println("file is not upload");
		} else {
			System.out.println("文件长度: " + myfiles.getSize());
			System.out.println("文件类型: " + myfiles.getContentType());
			System.out.println("文件名称: " + myfiles.getName());
			System.out.println("文件原名: " + myfiles.getOriginalFilename());
			String filePath = "";
			
			filePath = upload(desImgPath, myfiles,false);
			imgItem.setProductId(productId);
			imgItem.setImgPath(filePath);
			((List<ProductImgList>) request.getSession().getAttribute("itemlist")).add(imgItem);
		}
		return "{\"proId\":\"" + productId + "\"}";
	}

	private String upload(String path, MultipartFile file,boolean smallFlag) {
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String fileName = UUID.randomUUID().toString() + suffix;
		try {
			 if(smallFlag){
				 File destDir = new File(path+"/min/");
				 destDir.mkdir();
				 Thumbnails.of(file.getInputStream()).size(230,
				 230).toFile(path+"/min/"+fileName);
			 }else{
				 Files.copy(file.getInputStream(), Paths.get(path, fileName));
			 }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error";
		}
		return fileName;
	}
	//显示商品添加页面
	@RequestMapping("/addpro")
	public String addpro(HttpServletRequest request, Model model) {
		//查询所有商品的类型
		model.addAttribute("typeList", productService.getTypeList());
		//查找所有的供货商
		model.addAttribute("supplierInfos",productService.findSupplierName());
		int ran = (int) (Math.random() * 9000) + 1000;
		//定义商品的编号。使用月份和天数进行拼接
		String productId = "YS" + DateUtils.currentDate("MMdd") + ran;
		request.getSession().setAttribute("productId", productId);
		model.addAttribute("productId", productId);
		//创建一个商品图片的集合
		List<ProductImgList> itemList = new ArrayList<ProductImgList>();
		request.getSession().setAttribute("itemlist", itemList);
		return "/mng/main/product/addpro";
	}
	
	@RequestMapping("/goup")
	public String changeprostatus(String pid,Integer status, Model model) {
		ProductInfo productInfo = new ProductInfo();
		productInfo.setProductId(pid);
		productInfo.setProStatus(2);
		productService.updateProduct(productInfo);
		return "redirect:/product/toprolist";
	}
	@RequestMapping("/godown")
	public String godown(String pid,Integer status, Model model) {
		ProductInfo productInfo = new ProductInfo();
		productInfo.setProductId(pid);
		productInfo.setProStatus(1);
		productService.updateProduct(productInfo);
		return "redirect:/product/toprolist";
	}
	
	@RequestMapping("/sdel")
	public String sdel(String pid,Integer status, Model model) {
		productService.deleteProduct(pid);
		return "redirect:/product/toprolist";
	}
	
	@RequestMapping("/edit")
	public String edit(String pid,Integer status, Model model) {
		ProductInfo productInfo = productService.getProductById(pid);
		System.out.println("detail:"+productInfo.getDetail());
		model.addAttribute("typeList", productService.getTypeList());
		model.addAttribute("proInfo", productInfo);
		return "/mng/main/product/editpro";
	}
	
	@RequestMapping("/editpro")
	public String editpro(ProductInfo productInfo, Model model) {
		productService.updateProduct(productInfo);
		return "redirect:/product/toprolist";
	}



	@RequestMapping("/typelist")
	public String typelist(Model model) {
		model.addAttribute("typeList", productService.getTypeList());
		return "/mng/main/product/typelist";
	}

	@RequestMapping("/addtype")
	public String addtype(ProductTypeInfo productTypeInfo, Model model) {
		productService.addProductType(productTypeInfo.getTypeName());
		model.addAttribute("typeList", productService.getTypeList());
		return "/mng/main/product/typelist";
	}

	@RequestMapping("/deltype")
	public String deltype(Integer typeId, Model model) {
		productService.delProductType(typeId);
		model.addAttribute("typeList", productService.getTypeList());
		return "/mng/main/product/typelist";
	}
	

	//搜索商品
	@RequestMapping("/searchCommodity")
	public String  searchCommoditys(@RequestParam  String  searchName ,HttpServletRequest request ,Model  model) throws UnsupportedEncodingException{
//		 searchName=new String(searchName.getBytes("ISO-8859-1"),"utf-8");
		 System.out.println(searchName);
//		String searchName=request.getParameter("searchName")
		Map params=new HashMap();
		params.put("productName", searchName);
		params.put("startIndex",0);
		params.put("pageSize",10);
		 List<ProductInfo> productInfoLists=productService.searchCommoditys(params);
		 model.addAttribute("proList",productInfoLists);
			model.addAttribute("title", "搜索结果");
		return "mall/goodslist";
	}
	
	//修改商品的供货商视图显示
	@RequestMapping("/updateSupplierView")
	public String updateSupplierView(String productId, Model model){
		model.addAttribute("suppliers",productService.findSuppliers());
		//查询商品信息
		ProductInfo productInfo=productService.findProduct(productId);
		model.addAttribute("productInfo", productInfo);
		return "/mng/main/product/updatepro";
	}
	
	//修改商品的供应商
	@RequestMapping("updateSupplier")
	public String updateSupplier(ProductInfo productInfo){
		productService.updateProductSupplier(productInfo);
		return "redirect:/product/toprolist";
	}
	
	
}
